Page({
  data: {
    loginForm: {
      username: '',
      password: '',
      usernameType: 0, // 0: 用户名, 1: 邮箱
    },
    forgotPasswordForm: {
      mail: '',
      identifyingCode: '',
      newPassword: '',
      confirm: '',
    },
    MailForm: {
      mail: '',
    },
    fullscreenLoading: false,
    rememberMe: false,
    attempt: 3,
    defaultMessage: '验证失败,您还剩下3次机会',
    forgotPassword: false,
    isShow1: false,
    isShow2: false,
  },

  onLoad() {
    const dataStr = wx.getStorageSync('loginInfo');
    if (dataStr) {
      const data = JSON.parse(dataStr);
      this.setData({
        'loginForm.username': data.username,
        'loginForm.password': data.password,
        rememberMe: true,
      });
    }
  },

  onClose() {
    if (this.data.forgotPassword) {
      this.setData({ isShow2: false });
    } else {
      this.setData({ isShow1: false });
    }
  },

  getUser(accessToken) {
    const that = this;
    wx.request({
      url: 'http://202.192.19.106:8080/api/v2/users/list?flag=1',
      method: 'POST',
      header: { token: accessToken },
      success(res) {
        that.setData({ fullscreenLoading: false });
        if (res.data.code === 200) {
          const userData = res.data.data;
          wx.setStorageSync('user', userData);
          wx.setStorageSync('token', accessToken);

          if (userData.userRoleId === 4 || userData.userRoleId === 7) {
            wx.redirectTo({ url: '/pages/student/tests/tests' });
          } else if (userData.userRoleId === 2) {
            wx.redirectTo({ url: '/pages/school/center/schoolPreview/schoolPreview' });
          } else if (userData.userRoleId === 9) {
            wx.redirectTo({ url: '/pages/teacher/center/SchoolManagement/studentList/studentList' });
          } else {
            wx.redirectTo({ url: '/pages/nav/nav' });
          }
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      },
      fail() {
        that.setData({ fullscreenLoading: false });
        wx.showToast({ title: '发生未知错误,请稍后再试', icon: 'none' });
      }
    });
  },

  onSuccess() {
    this.onClose();
    this.setData({ fullscreenLoading: true });

    if (this.data.forgotPassword) {
      wx.request({
        url: 'http://202.192.19.106:8080/api/v2/users/recovery-password/verify',
        method: 'POST',
        data: {
          mail: this.data.forgotPasswordForm.mail,
          code: this.data.forgotPasswordForm.identifyingCode,
          newPassword: this.data.forgotPasswordForm.newPassword,
        },
        success: (res) => {
          this.setData({ fullscreenLoading: false });
          if (res.data.code === 200) {
            wx.showToast({ title: '更改密码成功,您现在可以使用新密码进行登录', icon: 'success' });
            this.setData({ forgotPassword: false });
            this.setData({
              'loginForm.username': this.data.forgotPasswordForm.mail,
              'loginForm.password': this.data.forgotPasswordForm.newPassword,
              rememberMe: true,
            });
          } else {
            wx.showToast({ title: res.data.msg, icon: 'none' });
          }
        },
        fail: () => {
          this.setData({ fullscreenLoading: false });
          wx.showToast({ title: '发生未知错误,请稍后再试', icon: 'none' });
        }
      });
    } else {
      wx.request({
        url: 'http://202.192.19.106:8080/api/v2/login',
        method: 'POST',
        data: {
          username: this.data.loginForm.username,
          password: this.data.loginForm.password,
        },
        success: (res) => {
          this.setData({ fullscreenLoading: false });
          if (res.data.code === 200) {
            if (this.data.rememberMe) {
              const loginInfo = JSON.stringify(this.data.loginForm);
              wx.setStorageSync('loginInfo', loginInfo);
            } else {
              wx.removeStorageSync('loginInfo');
            }
            this.getUser(res.data.data.accessToken);
          } else {
            wx.showToast({ title: res.data.msg, icon: 'none' });
          }
        },
        fail: () => {
          this.setData({ fullscreenLoading: false });
          wx.showToast({ title: '发生未知错误,请稍后再试', icon: 'none' });
        }
      });
    }
  },

  validateMail(value) {
    const regex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return value !== '' && regex.test(value);
  },

  validateUsername(value) {
    const regex = /^[a-zA-Z0-9!@#$%^&*()-_+=<>?]{4,20}$/;
    const regex2 = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return value !== '' && (regex.test(value) || regex2.test(value));
  },

  validatePassword(value) {
    const regex = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9!@#$%^&*()-_+=<>?]{8,20}$/;
    return value !== '' && regex.test(value);
  },

  validateIdentifyingCode(value) {
    return value !== '';
  },

  validateConfirm(value) {
    return value === this.data.forgotPasswordForm.newPassword;
  },

  login(formEl) {
    if (this.data.attempt <= 0) {
      wx.showToast({ title: '您近期操作频繁,请1分钟后再试', icon: 'none' });
      return;
    }

    if (!formEl) return;

    formEl.validate((valid) => {
      if (valid) {
        this.setData({ isShow1: true });
      }
    });
  },

  getIdentifyingCode(formEl) {
    if (!formEl) return;

    formEl.validate((valid) => {
      if (valid) {
        wx.request({
          url: 'http://202.192.19.106:8080/api/v2/users/recovery-password',
          method: 'POST',
          data: { mail: this.data.forgotPasswordForm.mail },
          success: (res) => {
            if (res.data.code === 200) {
              wx.showToast({ title: '已成功发送验证码,请注意查看', icon: 'success' });
            } else {
              wx.showToast({ title: res.data.msg, icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '发生未知错误,请稍后再试', icon: 'none' });
          }
        });
      }
    });
  },

  setNewPassword(formEl) {
    if (!formEl) return;

    formEl.validate((valid) => {
      if (valid) {
        this.setData({ isShow2: true });
      } else {
        wx.showToast({ title: '请合法输入所有信息', icon: 'none' });
      }
    });
  }
});
